package com.boby.homecamera.adapter;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class LimitedLinearLayoutManager extends LinearLayoutManager {
    private static final String TAG = "LimitedManager";
    private int maxScrollY = Integer.MAX_VALUE;
    private int totalScrollY = 0;
    private RecyclerView attachedRecyclerView;

    public LimitedLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public void setMaxScrollY(int maxScrollY) {
        this.maxScrollY = maxScrollY;
        // 若当前 total 超过新 max，修正
        if (totalScrollY > maxScrollY) totalScrollY = maxScrollY;
    }

    public int getMaxScrollY() {
        return maxScrollY;
    }

    public int getTotalScrollY() {
        return totalScrollY;
    }

    public void resetTotalScrollY() {
        totalScrollY = 0;
    }

    @Override
    public void onAttachedToWindow(RecyclerView view) {
        super.onAttachedToWindow(view);
        attachedRecyclerView = view;
    }

    @Override
    public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
        super.onDetachedFromWindow(view, recycler);
        attachedRecyclerView = null;
    }

    // 核心：用 totalScrollY 作为唯一可信的累计滚动值
    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        // 计算目标并 cap
        int desired = totalScrollY + dy;
        int realDy = dy;
        if (desired > maxScrollY) {
            realDy = maxScrollY - totalScrollY;
        } else if (desired < 0) {
            realDy = -totalScrollY;
        }

        // 调用父类实际滚动，返回实际消耗的像素
        int consumed = super.scrollVerticallyBy(realDy, recycler, state);

        // 用实际消耗值来累加（更可靠）
        totalScrollY += consumed;

        // debug 日志（如需堆栈，可打开下面行）
        Log.d(TAG, "scrollVerticallyBy dy: " + dy + ", realDy: " + realDy + ", consumed: " + consumed +
                ", totalScrollY: " + totalScrollY + ", maxScrollY: " + maxScrollY);

        return consumed;
    }

    // 当外部直接调用 layoutManager.scrollToPositionWithOffset 时，也做一次保护性修正
    @Override
    public void scrollToPositionWithOffset(final int position, final int offset) {
        // 先调用父类尝试定位（快速实现），再在下一帧修正（因为可能需要 layout 后才能拿到 view）
        super.scrollToPositionWithOffset(position, offset);
        if (attachedRecyclerView == null) return;

        attachedRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                View v = findViewByPosition(position);
                if (v == null) return;

                int desiredTop = attachedRecyclerView.getPaddingTop() + offset;
                int currentTop = v.getTop();
                int dy = currentTop - desiredTop;

                // cap dy
                int allowedDy = dy;
                if (totalScrollY + allowedDy > maxScrollY) {
                    allowedDy = maxScrollY - totalScrollY;
                } else if (totalScrollY + allowedDy < 0) {
                    allowedDy = -totalScrollY;
                }
                if (allowedDy != 0) {
                    attachedRecyclerView.scrollBy(0, allowedDy);
                    totalScrollY += allowedDy;
                }

                Log.d(TAG, "scrollToPositionWithOffset pos:" + position + ", offset:" + offset +
                        ", correctedDy:" + allowedDy + ", totalScrollY:" + totalScrollY);
            }
        });
    }

    // 布局完成后，用 computeVerticalScrollOffset 做一次同步（避免某些极端情况下不一致）
    @Override
    public void onLayoutCompleted(RecyclerView.State state) {
        super.onLayoutCompleted(state);
        if (attachedRecyclerView != null) {
            // 以系统估算值同步一次（通常这是合理的初始值）
            int systemOffset = attachedRecyclerView.computeVerticalScrollOffset();
            if (Math.abs(systemOffset - totalScrollY) > 5) { // 只有偏差明显时同步，避免频繁覆盖
                totalScrollY = systemOffset;
                Log.d(TAG, "onLayoutCompleted sync totalScrollY to systemOffset: " + systemOffset);
            }
        }
    }
}
